package com.shxc.smarttrade.old.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapter.PositionHistoryAdapter;
import com.shxc.smarttrade.old.bean.PositionHistory;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myview.MyFootView;
import com.shxc.smarttrade.old.myview.MyRefreshHeadView;
import com.shxc.smarttrade.old.myview.RecycleViewDivider;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/5/31.
 */

public class PositionHistoryActivity extends BaseActivity {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.x_recycler_view)
    XRecyclerView xRecyclerView;

    private LinearLayoutManager manager;
    private PositionHistoryAdapter adapter;
    private int page = 1;
    List<PositionHistory> positionHistoryListAdd = new ArrayList<>();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    List<PositionHistory> positionHistoryList = (List<PositionHistory>) msg.obj;
                    if (positionHistoryList.size() != 0) {
                        positionHistoryListAdd.addAll(positionHistoryList);
                        adapter.setDatas(positionHistoryListAdd);
                    } else {
                        if (xRecyclerView != null)
                            xRecyclerView.setNoMore(true);
                        showToast("已加载全部！");
                    }
                    if (xRecyclerView != null)
                        xRecyclerView.refreshComplete();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_position_history);
        initView();
        initDatas(SpUtils.getInt(getApplicationContext(), "userId"), page, 10);
        initListener();
    }

    /**
     * 初始化数据
     */
    private void initView() {
        tvCenter.setText("交易记录");
        manager = new LinearLayoutManager(this);
        xRecyclerView.setLayoutManager(manager);
        xRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayout.VERTICAL, 20, getResources().getColor(R.color.all_background)));
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        MyRefreshHeadView myRefreshHeadView = new MyRefreshHeadView(this);
        myRefreshHeadView.setArrowImageView(R.mipmap.indicator_arrow);
        xRecyclerView.setRefreshHeader(myRefreshHeadView);
        xRecyclerView.setFootView(new MyFootView(this));
        xRecyclerView.setAdapter(adapter = new PositionHistoryAdapter(this));
    }

    /**
     * 初始化数据
     */
    private void initDatas(int userId, int page, int pagesize) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("userId", userId + "");
        map.put("page", page + "");
        map.put("pagesize", pagesize + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.POSITION_HISTORY_ACTIVITY_HISTORYORDER, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();

                    if (errCode.equals("0")) {
                        if (!jsonObject.get("data").isJsonNull()) {
                            JsonObject data = jsonObject.get("data").getAsJsonObject();
                            if (!data.get("historyOrder").isJsonNull()) {
                                JsonArray historyOrder = data.get("historyOrder").getAsJsonArray();
                                TypeToken typeToken = new TypeToken<List<PositionHistory>>() {
                                };
                                Type type = typeToken.getType();
                                Gson gson = new Gson();
                                List<PositionHistory> positionHistoryList = gson.fromJson(historyOrder, type);
                                Message msg = Message.obtain();
                                msg.what = 0;
                                msg.obj = positionHistoryList;
                                handler.sendMessage(msg);
                            }
                        } else {
                            showToast(R.string.data_error);
                        }
                    } else {
                        showToast(errMsg);
                    }
                }
            }
        });
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        positionHistoryListAdd.clear();
                        page = 1;
                        initDatas(SpUtils.getInt(getApplicationContext(), "userId"), page, 10);
                    }
                }, 1000);
            }

            @Override
            public void onLoadMore() {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initDatas(SpUtils.getInt(getApplicationContext(), "userId"), page, 10);
                    }
                }, 1000);
            }
        });
    }

    @OnClick(R.id.rl_left)
    public void rlLeft() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
